import dva from 'dva';
import {candidateSearch, removeCandidate, createCandidate} from '../services/vote';

export default {
  namespace: 'candidates',
  state: {
    loading: true,
    list: [],
    error: ''
  },
  reducers: {
    search(state, {payload: {data: data}}) {
      return {...state, ...data.data, ...{loading: false}};
    },
    removeReducer(state, {payload: {id, data}}) {
      if (data.code == 204) {
        return {...state, ...{list: state.list.filter(item => item.id !== id)}};
      }

      return {...state, ...{error: '删除失败'}};
    },
    createReducer(state, {payload: {data}}) {
      if (data.code == 201) {
        return {...state, ...{error: ''}};
      }
      return {...state, ...{error: data.data.error}};
    },
    startLoading(state, {payload: {}}){
      return {...state, ...{loading: true}};
    }
  },
  effects: {
    *fetch({payload: {page}}, {call, put}) {
      const {data} = yield call(candidateSearch, {page});
      yield put({type: 'search', payload: {data: data}});
    },
    *remove({payload: {id}}, {call, put}) {
      const {data} = yield call(removeCandidate, {id});
      yield put({type: 'removeReducer', payload: {id: id, data:data}});
    },
    *create({payload: query}, {call, put}) {
      const {data} = yield call(createCandidate, query);
      yield put({type: 'createReducer', payload: data});
    }
  },
  subscriptions: {
    setup({dispatch, history}) {
      return history.listen(({pathname, query}) => {
        if (pathname === '/votemodify' || pathname === '/voteadd' || pathname === '/candidates') {
          dispatch({type: 'fetch', payload: query});
        }
      });
    }
  },
};
